﻿/**********************************************************************************
 * Project Name :   
 * Remarks      :  
 * Class Name   :  UtilityConvert   
 * Version      :  v1.0.0.0 
 * Author       :  Joey Liang 
 * Description  : 
 * Created Time :  2013/5/22 0:24:49
 * Update Man   :  Joey Liang
 * Update Time  :  2013/5/22 0:24:49
************************************************************************/

using System;

namespace JoeyLibs.Utility
{
    /// <summary>
    /// 数据转化帮助类
    /// </summary>
    public class UtilityConvert
    {
        /// <summary>
        /// 将object转化string
        /// <param name="isTrim">是否去掉前后空格</param>
        /// </summary>
        public static string ObjectToString(object obj, bool isTrim = false)
        {
            string str = string.Format("{0}", obj);
            if (isTrim)
            {
                str = str.Trim();
            }

            return str;
        }

        /// <summary>
        /// 泛型类型转化。 Note：此类可能存在性能问题,可考虑通过枚举各种常用类型来转化(使用is关键字)
        /// </summary>
        /// <typeparam name="TReturn">转化后的类型</typeparam>
        /// <typeparam name="TSource">原类型</typeparam>
        /// <param name="source">原值</param>
        /// <returns>转化后的值</returns>
        public static TReturn ChangeType<TReturn, TSource>(TSource source)
        {
            return (TReturn)Convert.ChangeType(source, typeof(TReturn));
        }

        /// <summary>
        /// 尝试进行泛型类型转化。
        /// </summary>
        /// <typeparam name="TReturn">转化后的类型</typeparam>
        /// <typeparam name="TSource">原类型</typeparam>
        /// <param name="source">原值</param>
        /// <returns>转化后的值</returns>
        public static bool TryChangeType<TReturn, TSource>(TSource source, out TReturn result)
        {
            try
            {
                result = ChangeType<TReturn, TSource>(source);
                return true;
            }
            catch (Exception)
            {
                result = default(TReturn);
                return false;
            }
        }
    }
}
